<?php
/**
 * Created by PhpStorm.
 * User: jochen
 * Date: 2017/1/13
 * Time: 下午3:10
 */

namespace EWeiLink\JuPai\Services;


use EWeiLink\JuPai\Company;
use EWeiLink\JuPai\Contact;
use EWeiLink\JuPai\JuPai;
use EWeiLink\JuPai\Message;
use EWeiLink\JuPai\Planner;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\DB;

class ContactRepo
{

    public function list($filter = [], $pageSize = 20)
    {
        return Contact::where($filter)->paginate($pageSize);
    }

    /**
     * 获取联系人列表带搜索条件
     * @param $filter
     * @return array
     */
    public function getContactList($filter)
    {
        /**@var Collection $contacts */
        $user = request()->user();
        $perPage = array_get($filter, 'per_page', 20);
        if ($user->isInitUser()) {
            if ($perPage === 0) {
                $data = Contact::all();
                $total = $data->count();
                return compact('total', 'data');
            }
            $plannerId = array_get($filter, 'plannerId', null);
            $findName = array_get($filter, 'contactName', null);
            $bindState = array_get($filter, 'bindState', null);
            return Contact::findByNickName($findName)
                ->findByJpName($findName, 'or')
                ->findByPlannerId($plannerId)
                ->findByBindState($bindState)
                ->paginate(20);
        }
        $planner = null;
        if (!empty($user)) {
            $planner = Planner::findByUser($user)->first();
        }
        $data = [];
        $total = 0;
        if (!is_null($planner)) {
            /**@var Collection $data */
            $data = $planner->contacts;
            $total = is_null($data) ? 0 : $data->count();
        }
        return compact('total', 'data');
    }

    public function find($id)
    {
        return Contact::find($id);
    }
    
    public function getContactMessage($contact_id) {

        $filter = JuPai::callBridgeHelper('get_filter', []);
        if (is_null($filter)) {
            $filter = [];
        }

        $page = request()->input('page', 1);
        $user = request()->user();
        if (!$user->isInitUser()) {
            return [];
        }

        if ($page === '0') {
            $allData = Message::search($filter)
                ->where([
                    '$or' => [
                        ['to' => $contact_id],
                        ['from' => $contact_id]
                    ],
                ])->get();
            return [
                'total' => $allData->count(),
                'data' => $allData
            ];

        }

        return Message::search($filter)
            ->where([
                '$or' => [
                    ['to' => $contact_id],
                    ['from' => $contact_id]
                ],
            ])->paginate(20);

    }
}
